/**
 * Geo List Module.
 */
define([
  'jquery'
], function($) {
	var GeoList, checkedStatus;
	GeoList = (function() {
		function GeoList() {
		}
    checkedStatus = function(checkListLength, checkedListLength, callback) {
      var status = 0;
      if(checkListLength === checkedListLength) {
          // Check all.
          status = 1;
      } else if(checkedListLength === 0) {
          // None checked.
          status = 0;
      } else if(checkListLength >= checkedListLength) {
          // Half checked.
          status = -1;
      }
      if(callback && typeof callback === 'function') {
          callback(status);
      }
    };
		GeoList.prototype.init = function($geoIntervalWrap) {
      this.ckbCascade($geoIntervalWrap);
    };
		GeoList.prototype.listRender = function($geoIntervalWrap, data) {
      var i = 0, len = data.length, ckbRows = '',level=true;
      $geoIntervalWrap.children().filter(':gt(0)').remove();
      for (i = 0; i < len; i++) {
        var rows = data[i],
          rowTitle = rows.rank,
          rowCities = rows.cities,
          subCities,
          level2=true,halfCheckClass2="",
          level3=true, halfCheckClass3="",
          rowStr = '',
          checkedNum = 0,
          j, l = rowCities.length;

        for (j = 0; j < l; j++) {
          var item = rowCities[j],
            itemStr = '',
            checkedStr = '',
            subTotalStr = '',
            subCheckedNum = 0,
            k, lk;
          level3 = true;
          halfCheckClass3 = "";
          level2 &= item.status;
          subCities = rowCities[j].sub;
          lk = subCities.length;

          if (subCities.length !== 0) {
            var subStr = '';
            for (k = 0; k < lk; k++) {
              var sub = subCities[k],
                subChecked = '';
              if (sub.status) {
                subChecked = 'checked';
                subCheckedNum++;
              };
              level3 &= sub.status;
              subStr = '<li><div class="checkbox"><label>'
                      + '<input type="checkbox" name="geo" value="' + sub.id + '" ' + subChecked + ' >' + sub.name + '</label>'
                      + '</div></li>';
              subTotalStr += subStr;
            };
            item.status = (subCheckedNum === lk) ? true : false;
            
            subTotalStr = '<div class="popover bottom" style=""><div class="arrow"></div><div class="popover-content">'
                        + '<ul class="list-unstyled list-inline">'
                        + subTotalStr
                        + '</ul></div></div>';
            // console.log(subTotalStr);
          };
          if (item.status) {
            checkedStr = 'checked';
            checkedNum++;
          };
          halfCheckClass3 = (level3 || !subCheckedNum) ? '' : 'half-checked';
          if (!!halfCheckClass3) {
            halfCheckClass2 = "half-checked";
          }
          level2 &= level3;
          itemStr = '<div class="col-xs-1"><div class="geo-eles">'
               + '<input type="checkbox" class="" name="geo" value="' + item.id + '" ' + checkedStr + '> ' 
               + '<label class="' + halfCheckClass3 + '">'+ item.name + '</label></div>' + subTotalStr + '</div>';
          rowStr += itemStr;
        };
        if (!!halfCheckClass2) {
          halfCheckClass2 = 'half-checked';
        } else {
          halfCheckClass2 = (level2 || !checkedNum) ? '' : 'half-checked';
        }
        level &= level2;

        rowStr = '<div class="row rank-two"><div class="col-xs-1 pd0">'
               + '<label class="checkbox-inline ' + halfCheckClass2 + '">'
               + '<input type="checkbox" class="ckb-rank-all" ' + (l === checkedNum ? 'checked':'') + '> ' + rowTitle + '：</label></div>' 
               + rowStr + '</div>';
        
        $geoIntervalWrap.append(rowStr);
      }

      if(!level){
        $('.ckb-all').prop('checked',false);
        $('.ckb-all').parent().addClass('half-checked');
      }else{
        $('.ckb-all').prop('checked',true);
        $('.ckb-all').parent().removeClass('half-checked');
      }
    };
    GeoList.prototype.ckbCascade = function($geoIntervalWrap) {
      // Top level control.
      $geoIntervalWrap.on('change', '.ckb-all', function(evt) {
        var $me = $(this),
          $allGeoCkbs = $me.parents('.row').siblings('.row').find('input'),
          $allGeoLabel = $me.parents('.row').siblings('.row').find('label');
        $allGeoCkbs.prop('checked', this.checked);

        for (var i=0;i<$allGeoLabel.length;i++) {
          $($allGeoLabel[i]).removeClass('half-checked');
        }
        $me.parent().removeClass('half-checked');
      });
      // 1st level control.
      $geoIntervalWrap.on('change', '.ckb-rank-all', function(evt){
        var $me = $(this),
          myLevLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all').length,
          myLevChkLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all:checked').length;
          $subLev = $me.parents('.pd0').siblings('.col-xs-1');

        callback = function(status) {
          if (status === 1){
            $('.ckb-all').prop('checked',true);
            $('.ckb-all').parent().removeClass('half-checked');
          } else if (status === -1) {
              $('.ckb-all').prop('checked',false);
              $('.ckb-all').parent().addClass('half-checked');
          } else if (status === 0) {
            $('.ckb-all').prop('checked',false);
            if (!$('.pd0 label').hasClass('half-checked')) {
              $('.ckb-all').parent().removeClass('half-checked');
            }
          }
        }
        $subLev.find('input').prop('checked', this.checked);
        $me.parent().removeClass('half-checked');
        $subLev.find('.geo-eles label').removeClass('half-checked');
        checkedStatus(myLevLength,myLevChkLength,callback); 
      });
      // 2nd level control.
      $geoIntervalWrap.on('change','.geo-eles input', function(evt){
        var $me = $(this),
          $myFather = $me.parents('.rank-two').find('.pd0');
          myLevLength = $myFather.siblings().length;
          myLevChkLength = $myFather.siblings().find('.geo-eles input:checked').length;
          $subLev = $me.parents('.geo-eles').siblings().find('input');
          
        callback = function(status) {
          if (status === 1) {
            $myFather.find('input').prop('checked',true);
            $myFather.find('label').removeClass('half-checked');
          } else if (status === -1) { 
            $myFather.find('input').prop('checked',false);
            $myFather.find('label').addClass('half-checked');
          } else if (status === 0) {
            $myFather.find('input').prop('checked',false);
            if (!$myFather.siblings().find('.geo-eles label').hasClass('half-checked')) {
              $myFather.find('label').removeClass('half-checked');
            }
          }
          //找上层的兄弟层
          myFatherLevLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all').length;
          myFatherChkLength = $me.parents('.geo-interval-wrap').find('.ckb-rank-all:checked').length;
          checkedStatus(myFatherLevLength,myFatherChkLength,parentCallback);
          $me.siblings('label').removeClass('half-checked');
        };
        parentCallback = function(status){
          if (status === 1){
            $('.ckb-all').prop('checked',true);
            $('.ckb-all').parent().removeClass('half-checked');
          }else{
            $('.ckb-all').prop('checked',false);
            $('.ckb-all').parent().addClass('half-checked');
          }
        };
        $subLev.prop('checked', this.checked);
        $me.siblings('label').removeClass('half-checked');
        checkedStatus(myLevLength,myLevChkLength,callback);
      });
      // 3rd level control
      $geoIntervalWrap.on('change','.list-inline input', function(evt){
        var $me = $(this);
          $myFather = $me.parents('.bottom').siblings('.geo-eles');
          $myGrandParent = $me.parents('.rank-two').find('.pd0');
          myLevLength = $me.parents('ul').find('li').length;
          myLevChkLength = $me.parents('ul').find('li input:checked').length;

        callback = function(status) {
          if (status === 1) {
            $myFather.find('input').prop('checked',true);
            $myFather.find('label').removeClass('half-checked');
          } else if (status === -1){
            $myFather.find('input').prop('checked',false);
            $myFather.find('label').addClass('half-checked');
            $myGrandParent.find('label').addClass('half-checked');
          } else if (status === 0) {
            $myFather.find('input').prop('checked',false);
            $myFather.find('label').removeClass('half-checked');
            $myGrandParent.find('label').removeClass('half-checked');
          }
          $myFatherLev = $myGrandParent.siblings();
          myFatherLevLength = $myFatherLev.length;
          myFatherChkLength = $myFatherLev.find('.geo-eles input:checked').length;
          checkedStatus(myFatherLevLength,myFatherChkLength,parentCallback);
        };
        parentCallback = function(status) {
          if (status === 1) {
            $myGrandParent.find('input').prop('checked',true);
            $myGrandParent.find('label').removeClass('half-checked');
          } else if(status === -1) {
            $myGrandParent.find('input').prop('checked',false);
            $myGrandParent.find('label').addClass('half-checked');
            $('.ckb-all').parents('label').addClass('half-checked');
          } else if(status === 0) {
            $myGrandParent.find('input').prop('checked',false);
            //$myGrandParent.find('label').removeClass('half-checked');
          }
          myGrandParentLevLength = $('.ckb-rank-all').length;
          myGrandParentChkLength = $('.ckb-rank-all:checked').length;
          grandPCallback(myGrandParentLevLength,myGrandParentChkLength,grandPCallback);
        };
        grandPCallback = function(status){
          if (status === 1) {
            $('.ckb-all').prop('checked',true);
            $('.ckb-all').parents('label').removeClass('half-checked');
          } else if(status === -1) {
            $('.ckb-all').prop('checked',false);
            $('.ckb-all').parents('label').addClass('half-checked');
          } else if (status === 0) {
            $('.ckb-all').prop('checked',false);
            $('.ckb-all').parents('label').removeClass('half-checked');
          }
        };
        checkedStatus(myLevLength, myLevChkLength, callback);
      });
      // Geo sub list operate.
      $geoIntervalWrap.on('click', '.geo-eles > label', function(evt) {
        var $me = $(this),
          $subList = $me.parent().siblings('.popover');
        evt.preventDefault();
        $('.popover').hide();
        $subList.show().hover(
          function() {},
          function() {
            $subList.hide();
          });
      });
    };

		return GeoList;
	})();

	return GeoList;
});